<?php

namespace app\admin\controller;

use app\common\model;
use app\common\controller\Backend;
use app\common\model\Grade;
use Endroid\QrCode\QrCode;
use GuzzleHttp\Client;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 班级
 *
 * Class Classes
 * @package app\admin\controller
 */
class Classes extends Backend
{
    /**
     * @var \app\common\model\Classes
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedRight = ['searchList', 'cxSelect', 'xmSelect', 'detail', 'choose', 'students', 'chooseAdd'];
    protected $schoolLimit = true;
    protected $relationSearch = true;
    protected $modelValidate = true;
    protected $modelSceneValidate = true;
    protected $gradeData = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Classes');

        $result = collection(Grade::all())->toArray();

        foreach ($result as $k => $v) {
            $this->gradeData[$v['id']] = $v['name'];
        }

        $this->view->assign('gradeData', $this->gradeData);

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->alias('classes')
                ->join('__SCHOOL__ school', 'school.id = classes.school_id')
                ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
                ->join('__CLASSROOM__ classroom', 'classroom.id = classes.classroom_id', 'left')
                ->join('__BUILDING__ building', 'building.id = classroom.building_id', 'left')
                ->join('__GARDEN__ garden', 'garden.id = building.garden_id', 'left')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->alias('classes')
                ->join('__SCHOOL__ school', 'school.id = classes.school_id')
                ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
                ->join('__CLASSROOM__ classroom', 'classroom.id = classes.classroom_id', 'left')
                ->join('__BUILDING__ building', 'building.id = classroom.building_id', 'left')
                ->join('__GARDEN__ garden', 'garden.id = building.garden_id', 'left')
                ->field('classes.*,grade.name grade_name,school.name school_name,classroom.name classroom_name,building.name building_name,garden.name garden_name')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if ($list) {
                $list = collection($list)->append(['type_text'])->toArray();

                $classes_ids = array_column($list, 'id');
                $result = \app\common\model\ClassStudent::whereIn('class_id', $classes_ids)
                    ->field('class_id,count(*) count')
                    ->group('class_id')
                    ->select();
                $student_data = [];
                foreach ($result as $key => $value) {
                    $student_data[$value['class_id']] = $value['count'];
                }

                foreach ($list as $key => $value) {
                    $list[$key]['student_count'] = isset($student_data[$value['id']]) ? $student_data[$value['id']] : 0;
                    $content = base64_encode(json_encode(['type' => 'classes', 'id' => $value['id']]));
                    $qrCode = new QrCode($content);
                    $list[$key]['qrcode'] = $qrCode->getDataUri();
                }

            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if ($this->schoolLimit && $this->schoolLimitFieldAutoFill) {
                    $params[$this->schoolLimitField] = $this->auth->school_id;
                }

                if (!isset($params['classroom_id'])) {
                    $this->error('请选择教室');
                }

                $classroom = \app\common\model\Classroom::get($params['classroom_id']);

                if (!$classroom) {
                    $this->error('您选择的教室不存在');
                }

                $params['type'] = $classroom->type;

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $result = $this->model->allowField(true)->save($params);


                    $teacher = \app\common\model\Teacher::get($params['headmaster']);

                    $client = new Client([
                        'base_uri' => config('suzhi.url'),
                        'timeout'  => 30,
                        'allow_redirects' => true
                    ]);
                    $response = $client->request('POST', '/platform/classes/add', [
                        'form_params' => [
                            'id' => $this->model->id,
                            'name' => $params['name'],
                            'school_id' => $params['school_id'],
                            'grade_id' => $params['grade_id'],
                            'user_id' => $teacher['user_id'],
                        ]
                    ]);
                    $response->getStatusCode();

                    if (!$result) {
                        Db::rollback();
                        $this->error();
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model
            ->alias('classes')
            ->join('__SCHOOL__ school', 'school.id = classes.school_id')
            ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
            ->join('__CLASSROOM__ classroom', 'classroom.id = classes.classroom_id', 'left')
            ->join('__BUILDING__ building', 'building.id = classroom.building_id', 'left')
            ->join('__GARDEN__ garden', 'garden.id = building.garden_id', 'left')
            ->field('classes.*,grade.id grade_id,school.id school_id,classroom.id classroom_id,building.id building_id,garden.id garden_id')
            ->where('classes.id', $ids)
            ->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $schoolIds = $this->getDataLimitSchoolIds();

        if (is_array($schoolIds)) {
            if (!in_array($row[$this->schoolLimitField], $schoolIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $classroom = \app\common\model\Classroom::get($params['classroom_id']);

                if (!$classroom) {
                    $this->error('您选择的教室不存在');
                }

                $params['type'] = $classroom->type;

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if ($row->headmaster) {
            $headmaster = \app\common\model\Teacher::alias('teacher')
                ->join('__USER__ user', 'user.id = teacher.user_id')
                ->where('teacher.id', $row->headmaster)
                ->find();
            if ($headmaster) {
                $row['headmaster_name'] = $headmaster->user->nickname;
            }
        }

        $this->assignconfig('admin', ['school_id' => $row->school_id]);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 联动搜索
     */
    public function cxSelect()
    {
        $school_id = $this->request->request('school_id');
        $grade_id = $this->request->request('grade_id');
        $type = $this->request->request('type');//1 普通行政班级 2 走班 3 公共班级

        if ($type) {
            $type = explode(',', $type);
            $this->model->whereIn('type', $type);
        }

        $result = $this->model
            ->where('school_id', $school_id)
            ->where('grade_id', $grade_id)
            ->select();

        $searchList = [];
        foreach ($result as $key => $value) {
            $searchList[] = ['value' => $value['id'], 'name' => $value['name']];
        }

        $this->success('', null, $searchList);
    }

    /**
     * 查看学生信息 （行政班级）
     *
     * @return string
     * @throws Exception
     */
    public function detail()
    {
        $class_id = $this->request->request('class_id', 0);

        //$this->assignconfig('admin', ['class_id' => $class_id]);
        return $this->view->fetch();
    }

    /**
     * 选择学生
     *
     * @return string
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public function choose()
    {
        $class_id = $this->request->request('class_id', 0);

        $classes = model\Classes::get($class_id);
        if (!$classes) {
            $this->error(__('班级不存在'), '');
        }

        if ($classes->type != model\Classes::TYPE_ZOU_BAN && $classes->type != model\Classes::TYPE_GONG_GONG) {
            $this->error(__('班级类型错误'), '');
        }

        $this->assignconfig('admin', ['class_id' => $class_id]);
        return $this->view->fetch();
    }

    public function students()
    {
        $class_id = $this->request->request('class_id', 0);
        $id = $this->request->request('id', 0);

        if ($this->request->isAjax()) {
            $list = model\Student::alias('a')
                ->join('__CLASS_STUDENT__ b', 'b.student_id = a.id and b.class_id = ' . $class_id, 'left')
                ->where('a.class_id', $id)
                ->where('b.id', null)
                ->field('a.id,a.name')
                ->select();

            $this->success('', '', $list);
        }

    }

    public function chooseAdd()
    {
        $class_id = $this->request->request('class_id', 0);

        $classes = model\Classes::get($class_id);
        if (!$classes) {
            $this->error(__('班级不存在'), '');
        }

        if ($classes->type != model\Classes::TYPE_ZOU_BAN && $classes->type != model\Classes::TYPE_GONG_GONG) {
            $this->error(__('班级类型错误'), '');
        }

        if ($this->request->isAjax()) {
            $student_ids = $this->request->request('student/a');

            $insert_data = [];
            foreach ($student_ids as $key => $student_id) {
                $insert_data[] = [
                    'class_id' => $class_id,
                    'student_id' => $student_id,
                ];
            }
            $classStudent = new model\ClassStudent();
            $flag = $classStudent->saveAll($insert_data);

            if ($flag) {
                $this->success();
            } else {
                $this->error();
            }

        }

        $this->assign('school_id', $classes->school_id);
        $this->assign('class_id', $class_id);
        return $this->view->fetch();
    }

    public function xmSelect()
    {
        $school_id = $this->request->request('school_id');

        $result = Grade::with(['classes' => function($query) use ($school_id) {
            $query->where('school_id', $school_id);
        }])->select();


        $data = [];
        foreach ($result as $key => $value) {
            $data[] = [
                'name' => $value['name'],
                'optgroup' => true,
                'click' => 'AUTO',
            ];

            foreach ($value['classes'] as $i => $class) {
                $data[] = [
                    'name' => $value['name'] . $class['name'],
                    'value' => $class['id'],
                ];
            }
        }

        $this->success('', null, $data);




    }

    public function selectpage()
    {
        return parent::selectpage();
    }

}
